import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'
import { asyncRoutes } from './router/index'// 引入所有的动态路由表(未经过筛选)

const whiteList = ['/login', '/404'] // 白名单

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  console.log(to.path, from.path)
  const token = store.state.user.token
  if (token) {
    if (to.path === '/lofin') {
      // 有tonken去登录页不让进,直接去主页
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log(menus)
        const filterRoutes = asyncRoutes.filter(route => {
          const routeName = route.children[0].name
          return menus.includes(routeName)
        })
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)

        store.commit('menu/setMenuList', filterRoutes)
        // 解决刷新出现的白屏bug
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        next()
      }
    }
  } else {
    // 没有tonken
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
